using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Reflection;
using System.Collections.Generic;

namespace ULSLogExtractor.Features.UlsLogExtractorFeature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>
    /// 

    [Guid("b19c79d4-a86e-49c0-b401-719dc460b94c")]
    public class UlsLogExtractorFeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;
            RegisterJobDefinition(web);
            CreateAreasAndCategories(web);

        }

        private static void CreateAreasAndCategories(SPWeb web)
        {
            SPFieldChoice areaField = web.Fields.GetFieldByInternalName("LogArea") as SPFieldChoice;
            SPFieldChoice categoryField = web.Fields.GetFieldByInternalName("LogCategory") as SPFieldChoice;
            BindingFlags bindings = BindingFlags.Static | BindingFlags.NonPublic;

            MethodInfo getAllDiagInfo = typeof(SPDiagnosticsService).GetMethod("GetAllDiagnosticsServices", bindings);
            IEnumerable<SPDiagnosticsServiceBase> diagnosticsServiceBases = getAllDiagInfo.Invoke(null, new object[] { SPFarm.Local }) as IEnumerable<SPDiagnosticsServiceBase>;

            foreach (SPDiagnosticsServiceBase diagServiceBase in diagnosticsServiceBases)
            {
                foreach (SPDiagnosticsArea area in diagServiceBase.Areas)
                {
                    if (!area.Hidden)
                    {
                        areaField.Choices.Add(area.Name);

                        SPDiagnosticsCollection<SPDiagnosticsCategory> categories = area.Categories;
                        foreach (SPDiagnosticsCategory category in categories)
                        {
                            if (!category.Hidden)
                                categoryField.Choices.Add(category.Name);
                        }
                    }
                }
            }

            areaField.Update(true);
            categoryField.Update(true);
        }

        private static void RegisterJobDefinition(SPWeb web)
        {
            ULSLogExtractJobDefinition job = new ULSLogExtractJobDefinition(web);
            SPMinuteSchedule schedule = new SPMinuteSchedule();
            schedule.Interval = 5;
            job.Schedule = schedule;
            job.Update();
        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWeb web = properties.Feature.Parent as SPWeb;

            SPJobDefinitionCollection jobDefinitions = web.Site.WebApplication.JobDefinitions;

            foreach (SPJobDefinition jobDefinition in jobDefinitions)
            {
                ULSLogExtractJobDefinition castedJobDefinition = jobDefinition as ULSLogExtractJobDefinition;
                if (castedJobDefinition != null)
                {
                    if (castedJobDefinition.WebUri.AbsoluteUri == web.Url)
                    {
                        castedJobDefinition.Delete();
                    }
                }
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
